package com.yuanda.erp9.syn.service.erp9.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuanda.erp9.syn.contant.RateCalculateConstants;
import com.yuanda.erp9.syn.contant.TableConstant;
import com.yuanda.erp9.syn.entity.CmsBrandsTempEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsInformationEntity;
import com.yuanda.erp9.syn.entity.CmsPricesEntity;
import com.yuanda.erp9.syn.helper.RetryOperateLogHelper;
import com.yuanda.erp9.syn.mapper.erp9.CmsBrandsTempMapper;
import com.yuanda.erp9.syn.mapper.erp9.CmsGoodsInformationMapper;
import com.yuanda.erp9.syn.mapper.erp9.CmsGoodsMapper;
import com.yuanda.erp9.syn.mapper.erp9.CmsPricesMapper;
import com.yuanda.erp9.syn.pojo.CmsGoodsPojo;
import com.yuanda.erp9.syn.service.erp9.GoodsService;
import com.yuanda.erp9.syn.util.CacheUtil;
import com.yuanda.erp9.syn.vo.PluginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.stream.Collectors;

/**
 * @ClassName GoodsServiceImpl
 * @Description
 * @Date 2022/11/15
 * @Author myq
 */
@Slf4j
@Service
@Scope("prototype")
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private CmsGoodsMapper cmsGoodsMapper;

    @Autowired
    private CmsPricesMapper cmsPricesMapper;

    @Autowired
    private CmsGoodsInformationMapper cmsGoodsInformationMapper;

    @Autowired
    private CmsBrandsTempMapper cmsBrandsTempMapper;

    @Autowired
    private RetryOperateLogHelper retryOperateLogHelper;

    @Value("${mysql.write_enable}")
    private boolean writeEnable;


    /**
     * @param pojos
     * @Description: 批量新增，为提高性能不开启事务
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/11/1613:24
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    //@InsertBatch
    @Override
    public void insertBatch(List<CmsGoodsPojo> pojos) {
        if(!writeEnable) {
            log.info("**********Mysql数据库写功能已关闭**********");
            return;
        }
        try {
            if (CollectionUtils.isEmpty(pojos)) {
                return;
            }
            // 新增goods
            List<CmsGoodsEntity> goodsCollect = pojos.parallelStream().map(CmsGoodsPojo::getCmsGoodsEntity).collect(Collectors.toList());
            // 添加新的goods数据
            cmsGoodsMapper.insertBatch(goodsCollect);
            // cmsGoodsInformation 实体类
            List<CmsGoodsInformationEntity> informationEntities = pojos.parallelStream().map(
                    e -> {
                        CmsGoodsInformationEntity cmsGoodsInformationEntity = e.getCmsGoodsInformationEntity();
                        cmsGoodsInformationEntity.setParams(JSON.toJSONString(cmsGoodsInformationEntity.getParams()));
                        return cmsGoodsInformationEntity;
                    }).collect(Collectors.toList());
            cmsGoodsInformationMapper.insertBatch(informationEntities);
            // 开始添加阶梯数据
            Vector<CmsPricesEntity> pricesEntities = new Vector<>();
            // 一个商品对应多个阶梯价格
            pojos.parallelStream().forEach(e -> {
                if (e.getCmsPricesEntityList() != null) {
                    pricesEntities.addAll(e.getCmsPricesEntityList());
                }
            });
            if (!CollectionUtils.isEmpty(pricesEntities)) {
                cmsPricesMapper.insertBatch(pricesEntities);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("批量新增数据异常：" + e.toString());
            retryOperateLogHelper.addAll(pojos, e.toString());
        } finally {
            pojos.clear();
        }


    }


    /**
     * @Description: 删除所有当前供应商的数据
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/12/710:18
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void deleteAll(List<String> goodDeletePk) {
        if (!CollectionUtils.isEmpty(goodDeletePk)) {
            // 删除goods表记录
            cmsGoodsMapper.deleteBatchIds(goodDeletePk);
            // 删除information表记录
            LambdaQueryWrapper<CmsGoodsInformationEntity> cmsGoodsInformationEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            cmsGoodsInformationEntityLambdaQueryWrapper.in(CmsGoodsInformationEntity::getGoodid, goodDeletePk);
            cmsGoodsInformationMapper.delete(cmsGoodsInformationEntityLambdaQueryWrapper);
            // 删除prices表记录
            LambdaQueryWrapper<CmsPricesEntity> cmsPricesEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            cmsPricesEntityLambdaQueryWrapper.in(CmsPricesEntity::getGoodid, goodDeletePk);
            cmsPricesMapper.delete(cmsPricesEntityLambdaQueryWrapper);

            log.info(">>>>>>>>>>>>>>>>>>>>>>>删除mysql数据成功>>>>>>>>>>>>>>>>>>>>>>>");
            goodDeletePk.clear();
        }
    }


    /**
     * @Description: 返回带删除的IDS
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/12/2010:48
     */
    @Override
    public List<String> queryDeleteIds(Integer supplierId, String hisp, Integer source) {
        List<CmsGoodsEntity> goodDeleteList;
        if (!StringUtils.isEmpty(hisp)) {
            goodDeleteList = cmsGoodsMapper.querySupplierIdAndHisp(supplierId, source, hisp);
        } else {
            // 根据供应商ID删除数据
            goodDeleteList = cmsGoodsMapper.querySupplierId(supplierId);
        }

        if (!CollectionUtils.isEmpty(goodDeleteList)) {
            return goodDeleteList.parallelStream().map(CmsGoodsEntity::getGoodid).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * @Description:
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2023/1/515:20
     */
    @Override
    public List<String> queryDeleteIds(Integer supplierId, Set<String> hispSet) {
        List<CmsGoodsEntity> goodDeleteList;
        if (!CollectionUtils.isEmpty(hispSet)) {
            goodDeleteList = cmsGoodsMapper.querySupplierIdAndHispSet(supplierId, hispSet);
        } else {
            // 根据供应商ID删除数据
            goodDeleteList = cmsGoodsMapper.querySupplierId(supplierId);
        }

        if (!CollectionUtils.isEmpty(goodDeleteList)) {
            return goodDeleteList.parallelStream().map(CmsGoodsEntity::getGoodid).collect(Collectors.toList());
        }
        return Collections.emptyList();

    }

    /**
     * @Description:
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2023/1/515:20
     */
    @Override
    public List<String> queryRsDeleteIds(Integer supplierId, Set<String> hispSet, Integer source) {
        List<CmsGoodsEntity> goodDeleteList;
        if (!CollectionUtils.isEmpty(hispSet)) {
            goodDeleteList = cmsGoodsMapper.queryRsSupplierIdAndHispSet(supplierId, source, hispSet);
        } else {
            // 根据供应商ID删除数据
            goodDeleteList = cmsGoodsMapper.queryRsSupplierId(supplierId);
        }

        if (!CollectionUtils.isEmpty(goodDeleteList)) {
            return goodDeleteList.parallelStream().map(CmsGoodsEntity::getGoodid).collect(Collectors.toList());
        }
        return Collections.emptyList();

    }

    /**
     * plugin表更改 影响goods表
     *
     * @param pluginVo
     */
    @Override
    public Integer updateRateByManufacturerAndModel(PluginVo pluginVo, String rate, Integer tariffsRate, BigDecimal inspectionChargesFee) {
        Integer updateNum = cmsGoodsMapper.updateRateByManufacturerAndModel(rate, tariffsRate, inspectionChargesFee, pluginVo.getManufacturer(), pluginVo.getPartNumber());
        log.info("plugin表更新goods:{} 条数据", updateNum);
        return updateNum;
    }

    @Override
    public Integer updateAllRate(String value) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(RateCalculateConstants.CUSTOMSEXCHANGERATE_FIELD);
        buffer.append("\":");
        buffer.append("\"" + value + "\"");
        buffer.append("}");
        Integer integer = cmsGoodsMapper.updateAllRate(buffer.toString(), RateCalculateConstants.CUSTOMSEXCHANGERATE_FIELD);
        log.info("plugin表更新goods:{} 条数据", integer);
        return integer;
    }

    /**
     * 根据Manufacturer和Model 查询已更改的数据
     *
     * @param pluginVo
     * @return
     */
    @Override
    public List<CmsGoodsEntity> findByManufacturerAndModel(PluginVo pluginVo) {
        LambdaQueryWrapper<CmsGoodsEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CmsGoodsEntity::getBrandName, pluginVo.getManufacturer());
        wrapper.eq(CmsGoodsEntity::getModel, pluginVo.getPartNumber());
        return cmsGoodsMapper.selectList(wrapper);
    }

    @Override
    public Integer findAllCount() {
        LambdaQueryWrapper<CmsGoodsEntity> wrapper = new LambdaQueryWrapper<>();
        return cmsGoodsMapper.selectCount(wrapper);
    }

    @Override
    public List<CmsGoodsEntity> findByLimit(Integer number, Integer pageSize) {
        return cmsGoodsMapper.findByLimit(number, pageSize);
    }

    /**
     * @Description: 批量新增之前优化设置
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/11/1713:31
     */
    @Override
    public void insertBatchBeforeSet() {
        cmsGoodsMapper.setAutocommit();
        cmsGoodsMapper.setBulkInsertBufferSize();
        // 没有权限
//        cmsGoodsMapper.setConcurrentInsert();
        cmsGoodsMapper.setForeignKeyChecks();
        cmsGoodsMapper.setUniqueChecks();
    }

    /**
     * @Description: 重置设置
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/11/1713:32
     */
    @Override
    public void insertBatchAfterReset() {
        cmsGoodsMapper.resetAutocommit();
        cmsGoodsMapper.resetBulkInsertBufferSize();
        // 没有权限
//        cmsGoodsMapper.resetConcurrentInsert();
        cmsGoodsMapper.resetForeignKeyChecks();
        cmsGoodsMapper.resetUniqueChecks();
    }

    /**
     * @Description: 清空表结构
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/11/1713:41
     */
    @Override
    public void truncateTable(String tableName) {
        cmsGoodsMapper.truncateTable(tableName);
    }

    /**
     * @Description: 根据name返回brand主键，调用方已经加锁，这里这不会再次加互斥锁了
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/11/2414:15
     */
    @Override
    public void getPKByBrandName(CmsBrandsTempEntity entity) {
        // 添加数据
        cmsBrandsTempMapper.insert(entity);
        // 缓存
        CacheUtil.Cache cache = CacheUtil.init(TableConstant.CMS_BRANDS_TEMP);
        cache.put(entity.getName(), entity.getBrandid());
    }

    /**
     * @Description: 根据name返回supplier主键
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/11/2414:15
     */
    @Override
    public Integer getPKBySupplierName(String supplierName) {
        return null;
    }
}